<?php

namespace App\Containers\AppSection\Confirmation\Actions;

use App\Containers\AppSection\Confirmation\Mails\SendCodeMail;
use App\Containers\AppSection\Confirmation\Models\Confirmation;
use App\Containers\AppSection\Confirmation\Tasks\CreateConfirmationTask;
use App\Containers\AppSection\Confirmation\Tasks\DeleteAllConfirmsByValueTask;
use App\Containers\AppSection\Confirmation\UI\API\Requests\SendEmailCodeRequest;
use App\Ship\Parents\Actions\Action;
use App\Ship\Phones\SmsRu;
use Illuminate\Support\Facades\Mail;

class SendEmailCodeAction extends Action
{
    public function run(SendEmailCodeRequest $request): Confirmation
    {
        $code = generateRandomInt(config('appSection-confirmation.code-length'));

        app(DeleteAllConfirmsByValueTask::class)
            ->run(
                $request->email,
                $request->getInputByKey('type'),
                config('appSection-confirmation.confirms.email.type')
            );

        $confirmation = app(CreateConfirmationTask::class)
            ->run([
                'code' => $code,
                'value' => $request->email,
                'request_type' => $request->getInputByKey('type'),
                'confirm_type' => config('appSection-confirmation.confirms.email.type'),
            ]);

        try {
            Mail::send(new SendCodeMail($code, $request->email));
        } catch (\Throwable $e) {

        }


        return $confirmation;
    }
}
